import { rgb2hex } from './utils.js';

const imagePreviewContainer = document.querySelector('#image-preview');
const mainCanvas = document.querySelector('#main-canvas');
const originSizeCanvas = document.querySelector('#origin-size-canvas');
const tempCanvas = document.createElement('canvas');

const mainCtx = mainCanvas.getContext('2d');
const originSizeCtx = originSizeCanvas.getContext('2d');
const tempCtx = tempCanvas.getContext('2d');

const CANVAS_WIDTH = 600;

let mainCanvasWidth = CANVAS_WIDTH;
let mainCanvasHeight = 0;

/** 图片缩放比例 */
let _ratio;

/** 缓存上一次获取的像素信息 */
let _lastPixelInfo;

let _onShowResult;

tempCanvas.width = 133;
tempCanvas.height = 133;

// 鼠标单击时显示取色结果
imagePreviewContainer.addEventListener('click', (e) => {
  _lastPixelInfo && _onShowResult && _onShowResult(_lastPixelInfo);
});

const renderImage = (image) => {
  // 绘制原始尺寸图片
  originSizeCanvas.width = image.width;
  originSizeCanvas.height = image.height;
  originSizeCtx.drawImage(image, 0, 0);

  // 绘制等比例调整尺寸后的图片
  const ratio = CANVAS_WIDTH / image.width;
  const renderHeight = image.height * ratio;
  mainCanvasHeight = renderHeight;
  mainCanvas.height = renderHeight;
  mainCtx.drawImage(image, 0, 0, CANVAS_WIDTH, renderHeight);

  _ratio = ratio;
};

// 绘制网格
const drawMesh = () => {
  tempCtx.beginPath();
  tempCtx.lineWidth = 1;
  for (let i = 1; i < 19; ++i) {
    tempCtx.moveTo(0, i * 7);
    tempCtx.lineTo(133, i * 7);
    tempCtx.moveTo(i * 7, 0);
    tempCtx.lineTo(i * 7, 133);
  }
  tempCtx.strokeStyle = 'grey';
  tempCtx.stroke();

  tempCtx.strokeStyle = 'black';
  tempCtx.strokeRect(7 * 9, 7 * 9, 7, 7);
}

// 获取鼠标点击位置的附近的放大预览图
export const getPixelPreviewImage = (x, y) => {
  x = Math.floor(x / _ratio);
  y = Math.floor(y / _ratio);
  let sx = x - 20;
  let sy = y - 20;
  let sw = 40;
  let sh = 40;
  tempCtx.drawImage(originSizeCanvas, sx, sy, sw, sh, 0, 0, tempCanvas.width, tempCanvas.height);
  drawMesh();
  return tempCanvas.toDataURL();
}

// 获取鼠标点击位置的像素颜色信息
export const getPixelInfo = (x, y) => {
  x = Math.floor(x / _ratio);
  y = Math.floor(y / _ratio);

  const pixelData = originSizeCtx.getImageData(x, y, 1, 1).data;
  const r = pixelData[0];
  const g = pixelData[1];
  const b = pixelData[2];
  const hex = rgb2hex(r, g, b);

  const pixelInfo = {
    r,
    g,
    b,
    hex,
  };
  _lastPixelInfo = pixelInfo;
  return pixelInfo;
}

export const getMainCanvasSize = () => {
  return {
    width: mainCanvasWidth,
    height: mainCanvasHeight
  };
};

export const renderPoint = (x, y) => {
  mainCtx.fillStyle = 'red';
  mainCtx.beginPath();
  mainCtx.arc(x, y, 3, 0, Math.PI * 2);
  mainCtx.fill();
};

export const showImage = (image) => {
  renderImage(image);
};

export const setOnShowResult = (onShowResult) => {
  _onShowResult = onShowResult;
};
